<template>
  <div id="container" style="padding: 10px; box-sizing: border-box">
    <div id="main" style="width: 100%; position: relative;" v-if="show">
      <template v-for="(pageGoods, pageGoodsIndex) in order_list">
        <div :key="'pageGoods' + pageGoodsIndex" style="width: 100%; position: relative">
          <!-- 标题 -->
          <div 
            v-if="tem_id == 9 && print_settings.fontset" 
            class="header" 
            style="height: 30px; lineheight: 30px;" 
            :style="{
              fontSize: print_settings.fontset.fontSize + 'px',
              fontWeight: print_settings.fontset.bold ? 'bold' : 'none',
              textDecoration: print_settings.fontset.underline ? 'underline' : 'none',
              fontStyle: print_settings.fontset.italic ? 'italic' : 'none',
              textAlign: print_settings.fontset.textAlign
            }"
          >
            {{ print_settings.page.headerTitle || "" }}
          </div>

          <div v-else class="header" style="font-size: 30px; height: 30px; lineheight: 30px;" :style="{ textAlign: a }">
            {{ print_settings.page.headerTitle || "" }}
          </div>

          <div style="clear: both"></div>
          <!-- 订单信息 -->
          <div style="width: 100%; position: absolute">
            <span
              v-for="(item, index) in getOrderList"
              :key="index"
              :style="{
                left: item.containerStyle.left,
                top: item.containerStyle.top,
                ...item.style,
                width: 'auto',
                height: 'auto',
                position: 'absolute',
                zIndex: '1',
              }"
            >
              <template v-if="item.name === '二维码'">
                <div id="qrcode"></div>
              </template>
              <template v-else>
                {{ item.name }}{{ item.isCustom ? "" : ":" }}{{ order[`${item.index - 1}`] }}
              </template>
            </span>
          </div>
          <div style="clear: both"></div>

          <!-- 线段 -->
          <div style="width: 100%; position: absolute">
            <span 
              v-for="(item, index) in getLineList"
              :key="index"
              style="position: absolute; z-index: 1;" 
              :style="{
                left: item.containerStyle.left,
                top: item.containerStyle.top,
                ...item.style,
                width:item.containerStyle.width,
                height:item.containerStyle.height,
                position: 'absolute',
                zIndex: 1,
              }"
            >
            </span>
          </div>
          <div style="clear: both"></div>

          <!-- 配送单商品信息 -->
          <div 
            class="goods" 
            style="width: 100%; margin: 0; padding: 0; position: relative" 
            :style="{  marginTop: tableHeight + 'px' }" 
            v-if="print_document_type == 'order' && print_settings.printSetting.is_category"
          >
            <!-- 分类 -->
            <table 
              style="
                margin: 0;
                margin-bottom: 6px;
                padding: 0;
                border-collapse: collapse;
                border-spacing: 0;
                border: 1px solid #000;
                border-bottom: 0;
                position: relative;
              "
              :style="{ left: tableContainerStyle.left }"
            >
              <tbody>
                <tr style="height: 25px; line-height: 25px" :style="getTableConfig.style">
                  <td style="border: 1px solid #000; padding: 0 5px">类别</td>
                  <td 
                    v-for="(category, categoryIndex) in category_list" 
                    :key="`category${categoryIndex}`"
                    style="border: 1px solid #000; padding: 0 5px"
                  >
                    {{ category.category_name }}
                  </td>
                </tr>
                <tr style="height: 25px; line-height: 1.5" :style="getTableConfig.style">
                  <td style="border: 1px solid #000; padding: 0 5px">商品数</td>
                  <td v-for="(category, categoryIndex) in category_list" :key="`category${categoryIndex}`" style="border: 1px solid #000; padding: 0 5px">
                    {{ category.class }}
                  </td>
                </tr>
              </tbody>
            </table>
            <!-- 商品 -->
            <table 
              style="
                width: 100%;
                margin: 0;
                padding: 0;
                border-collapse: collapse;
                border-spacing: 0;
                border: 1px solid #000;
                border-bottom: 0;
                position: relative;
              "
              :style="{ width: tableContainerStyle.width, left: tableContainerStyle.left }"
            >
              <tbody>
                <tr :style="{ ...getTableConfig.style, height: '25px' }">
                  <td v-for="(column, columnIndex) in getTableConfig.columns" :key="`column${columnIndex}`" :width="column.width" style="border: 1px solid #000;">
                    {{ column.name }}
                  </td>
                </tr>
                <template v-for="(goods, goodsIndex) in pageGoods">
                  <template v-if="democc(goods)">
                    <tr :key="`goods${goodsIndex}`" :style="{ ...getTableConfig.style, height: `${tableTrHeight}px` }">
                      <td v-for="(column, columnIndex) in getTableConfig.columns" :key="`column${columnIndex}`" :width="column.width" style="border: 1px solid #000; border-top: 0">
                        {{ goods[`${column.index - 1}`] }}
                      </td>
                    </tr>
                  </template>
                  <template v-else>
                    <tr :key="`goods${goodsIndex}`" :style="{ ...getTableConfig.style, height: `${tableTrHeight}px` }">
                      <td style="border: 1px solid #000;border-top: 0;padding-left: 15px;" colspan="30">
                        {{ goods.category_name }}小计：{{ goods.money }}
                      </td>
                    </tr>
                  </template>
                </template>
              </tbody>
            </table>
          </div>

          <!-- 除配送单外的商品信息 -->
          <div 
            class="goods" 
            style="width: 100%; margin: 0; padding: 0" 
            :style="{ marginTop: tableHeight + 'px' }"
            v-else
          >
            <table 
              style="
                width: 100%;
                margin: 0;
                padding: 0;
                border-collapse: collapse;
                border-spacing: 0;
                border: 1px solid #000;
                border-bottom: 0;
                position: relative;
              "
              :style="{ width: tableContainerStyle.width, left: tableContainerStyle.left }"
            >
              <tbody>
                <tr :style="{ ...getTableConfig.style, height: '25px' }">
                  <template v-if="tem_id == 9 && print_settings.printSetting.doublePrinting == 1">
                    <td v-for="(two, oindex) in newtablist" :key="`o${oindex}`" style="border: 1px solid #000;">
                      {{ two.name }}
                    </td>
                    <td v-for="(two, oindex) in newtablist" :key="`o${oindex}1`" style="border: 1px solid #000">
                      {{ two.name }}
                    </td>
                  </template>
                  <template v-else>
                    <td v-for="(one, oindex) in getTableConfig.columns" :key="`o${oindex}`" style="border: 1px solid #000" :width="one.width">
                      {{ one.name }}
                    </td>
                  </template>
                </tr>
                <tr v-for="(item, indexs) in pageGoods" :key="`page${indexs}`" :style="getTableConfig.style">
                  <template v-if="tem_id == 9 && print_settings.printSetting.doublePrinting == 1">
                    <template v-if="Object.keys(pageGoods).length >= (item[0] - pageGoodsIndex * lineNumber) * 2">
                      <td 
                        v-for="(father, columnIndex) in getTableConfig.columns" 
                        :key="`column${columnIndex}`" 
                        style="border: 1px solid #000; border-top: 0"
                        :height="tableTrHeight"
                      >
                        <div v-if="showPageHeader">
                          {{
                            pageGoods[
                            (item[0] * 2 -
                              1 -
                              1 -
                              pageGoodsIndex * lineNumber) %
                            lineNumber
                            ] &&
                            pageGoods[
                            (item[0] * 2 -
                              1 -
                              1 -
                              pageGoodsIndex * lineNumber) %
                            lineNumber
                            ][1]
                            ? pageGoods[
                            (item[0] * 2 -
                              1 -
                              1 -
                              pageGoodsIndex * lineNumber) %
                            lineNumber
                            ][`${father.index - 1}`]
                            : ""
                          }}
                        </div>
                        <div v-else>
                          {{
                            pageGoods[
                            item[0] * 2 - 1 - pageGoodsIndex * lineNumber
                            ][1]
                            ? pageGoods[
                            item[0] * 2 - 1 - pageGoodsIndex * lineNumber
                            ][`${father.index - 1}`]
                            : ""
                          }}
                        </div>
                      </td>
                      <td 
                        v-for="(fathers, columnIndex) in getTableConfig.columns" :key="`column${columnIndex}1`" 
                        style="
                          border: 1px solid #000;
                          border-top: 0;
                          height: 30px;
                        "
                      >
                        <div v-if="showPageHeader">
                          {{
                            (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                            lineNumber !=
                            0 &&
                            pageGoods[
                            (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                            lineNumber
                            ] &&
                            pageGoods[
                            (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                            lineNumber
                            ][1]
                            ? pageGoods[
                            (item[0] * 2 -
                              1 -
                              pageGoodsIndex * lineNumber) %
                            lineNumber
                            ][`${fathers.index - 1}`]
                            : ""
                          }}
                        </div>
                        <div v-else>
                          {{
                            pageGoods[
                            item[0] * 2 - pageGoodsIndex * lineNumber
                            ][1]
                            ? pageGoods[
                            item[0] * 2 - pageGoodsIndex * lineNumber
                            ][`${fathers.index - 1}`]
                            : ""
                          }}
                        </div>
                      </td>
                    </template>
                  </template>
                  <template v-else>
                    <td 
                      v-for="(its, columnIndex) in getTableConfig.columns" 
                      :key="`column${columnIndex}`" 
                      style="border: 1px solid #000; border-top: 0;" 
                      :width="its.width"
                      :height="tableTrHeight"
                    >
                      {{ item[`${its.index - 1}`] }}
                    </td>
                  </template>
                </tr>
              </tbody>
            </table>
          </div>
          <div style="clear: both"></div>

          <!-- 合计 -->
          <div class="count">
            <table 
              style="
                width: 100%;
                margin: 0;
                padding: 0;
                border: 1px solid #000;
                border-bottom: 0;
                border-top: 0;
                border-spacing: 0;
                border-collapse: collapse;
                position: relative;
              "
              :style="{ width: tableContainerStyle.width, left: tableContainerStyle.left }"
            >
              <tbody>
                <tr :style="{ ...getTableConfig.style, height: '25px' }">
                  <td 
                    style="border: 1px solid #000; border-top: 0" 
                    v-for="(item, index) in getTableConfig.countList"
                    :key="index" 
                    :width="item.width" 
                    :style="item.style"
                  >
                    <div v-if="item.index == 4 && showPageHeader && tem_id == 9">
                      {{ item.name }}:{{ pageGoods.total }}
                    </div>
                    <div v-else-if="item.index > 4 && tem_id == 9">
                      {{ item.name }}:{{ all[`${item.index - 2}`] }}
                    </div>
                    <div v-else>
                      {{ item.name }}:{{ all[`${item.index - 1}`] }}
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- 签字信息 -->
          <div class="sign" style="width: 100%; position: absolute; clear: both;left: 0;" :style="{ height: signHeight+'px'}">
            <span
              v-for="(item, index) in getSignList"
              :key="index"
              style="position: absolute;overflow: hidden;z-index: 1;letter-spacing: 1px;"
              :style="{
                left: item.containerStyle.left,
                top: item.top + 'px',
                ...item.style,
                width: 'auto',
                height: 'auto',
                lineHeight: 'none'
              }"
            >
              <span v-if="item.isCustom">{{ item.name }}</span>
              <span v-else>{{ item.name | remove }} {{ item.name=='制单员'? $store.getters.name : '' }}</span>
            </span>
          </div>
          <div :style="{height: signHeight+'px'}"></div>
          <div :style="{ marginBottom: topMargin + 'px' }"></div>
          <p style="font-size: 14px; text-align: center;position: absolute;top: 5px;right: 20px;" v-if="showPageHeader">
            第{{ pageGoodsIndex + 1 }}页，共{{ order_list.length }}页
          </p>
        </div>
      </template>
    </div>

    <!-- <div id="left" v-if="print_settings.printSetting.isLeftTurn90==true">

    </div> -->
  </div>
</template>

<script>
import { getLodop } from "@/utils/LodopFuncs";
import {
  order_print,
  orderPrint,
  historyPrint,
  purchase_print,
  purchase_return_print,
  sort_print,
  statement_print,
  account_list_print,
  advice_list_print,
  sort_user_print,
  cash_delivery_order_print, //货到付款账单---订单
  online_payment_order_print, //在线支付账单---订单
  order_return_print, //订单退货单
  storage_print, //入库单打印
  stockout_print, // 出库单打印
} from "@/api/order/orderList";
import { batch_unbind_print, printEmpty } from "@/api/financial/finaicalOther";
import { get_print_mark } from "@/api/global/globalPrint";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { mapGetters } from "vuex";
import QRCode from "qrcodejs2";
export default {
  data() {
    return {
      a: "center",
      id: "",
      show: false,
      print_document_type: "", //打印的表单类型
      // 配送大写
      all: [],
      // 模板数据
      main_settings: {
        countSetData: {
          countlist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center"
          }
        },
        goodsSetData: {
          goodslist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center"
          }
        },
        mainSetData: {
          mainlist: {
            countlist: {},
            signlist: {},
            goodslist: {},
            orderlist: {}
          }
        },
        orderSetData: {
          orderlist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center"
          }
        },
        signSetData: {
          signlist: [],
          fontset: {
            fontSize: "14",
            bold: false,
            underline: "false",
            italic: false,
            textAlign: "center"
          }
        }
      },
      // 商品表单处理过的数据
      sortgoods: [],
      print_settings: {
        page: {},
        printSetting: {
          is_category: false,
          doublePrinting: ""
        },
        fontset: {
          fontSize: "14",
          bold: false,
          underline: "false",
          italic: false,
          textAlign: "center"
        }
      },
      order: "",
      order_list: "",
      category_list: [], //分类

      // 打印机配置信息
      print_set_info: [],
      // 是否连续打印
      continuous: false,
      // 预览
      preview: false,
      // 分页打印
      lineNumber: 0,
      topMargin: 10,
      tableTrHeight: 25,
      // 是否分页打印
      showPageHeader: false,
      tem_id: "",
      newtablist: [],
      total: "",
      tableHeight: 0, // 表格距离上面的外边距
      signHeight: 0 // 距离表格的最大高度
    };
  },
  computed: {
    ...mapGetters(["avatar"]),
    print_setting() {
      return `print_setting_list_${this.avatar.company_id}`;
    },
    // 订单信息
    getOrderList({ main_settings }) {
      return main_settings.filter(item => item.type == "inputCheck" || item.type == "input");
    },
    // 线段信息
    getLineList({ main_settings }) {
      return main_settings.filter(item => item.type == "line");
    },
    // 签字信息
    getSignList({ main_settings }) {
      return main_settings.filter(item => item.type == "sign");
    },
    // 表格信息
    getTableConfig({ main_settings }) {
      return main_settings.find(item => item.type === "table");
    },
    // 表格样式
    tableContainerStyle({ getTableConfig }) {
      return getTableConfig.containerStyle || {};
    },
  },
  filters: {
    remove: function (data) {
      if (data.indexOf("：") != -1 || data.indexOf(":") != -1) {
        return data;
      } else {
        return data + ":";
      }
    }
  },
  mounted() {
    this.monitoring(); // 注册监听事件
  },
  created() {
    // this.getTemplateData({ id: 1407, type: "order", uid: 339 });
  },
  methods: {
    democc(data) {
      if (data.category_name) {
        return false;
      } else {
        return true;
      }
    },
    monitoring() {
      // 监听事件
      this.$on("demo",async res => {
        this.get_print_info();
        await this.getTemplateData(res);
        if(res.cd) {
          res.cd(res.id);
        }
      });
    },
    // 获取打印机配置信息
    get_print_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name
      );
      let print_setting_list = localStorage.getItem(this.print_setting);
      if (print_setting_list) {
        try {
          this.print_set_info = JSON.parse(print_setting_list);
        } catch (error) {
          console.log(error);
        }
      }
      // get_print_mark(data).then((res) => {
      // 	if (res.errcode == 0) {
      // 		this.print_set_info = res.data.list;
      // 	}
      // });
    },
    // 数组分割
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      let suLength = Number(subGroupLength);
      if (this.showPageHeader) {
        if (Array.isArray(array)) {
          while (index < array.length) {
            newArray.push(array.slice(index, (index += suLength)));
          }
        } else {
          let arr = Object.values(array) ? Object.values(array) : [];
          while (index < arr.length) {
            newArray.push(arr.slice(index, (index += suLength)));
          }
        }
      } else {
        newArray = [array];
      }
      if (this.showPageHeader && this.tem_id == 9) {
        newArray.map(e => {
          e.total = 0;
          let total = 0;
          e.map(c => {
            total += Number(c[9]) || 0;
          });
          e.total = this.$toFixed(total);
        });
      }
      return newArray;
    },
    // 处理分类数据
    handleCategory(array) {
      let newArray = [];
      array.map(e => {
        let values = Object.values(e.list) ? Object.values(e.list) : [];
        values.map(async i => await newArray.push(i));
        let obj = {
          category_name: e.category_name,
          class: e.class,
          money: e.money
        };
        newArray.push(obj);
      });
      return this.group(newArray, this.lineNumber);
    },
    // 加载数据
    async getTemplateData(res) {
      let id = res.id;
      let uid = res.uid;
      let nickname = res.nickname
      this.print_document_type = res.type;
      let type = res.type;
      this.continuous = res.continuous;
      this.preview = res.preview;
      let data = packApi({ id, uid, nickname });
      if (res.type == "sortuser") {
        data = packApi({ oid: id, sort_rule: res.sort_rule });
      }
      // 获取数据函数
      let getFunc = "";
      switch (type) {
        case "order":
          getFunc = order_print;
          break;
        case "orderPrint": 
          getFunc = orderPrint;
          break;
        case "historyPrint":
          getFunc = historyPrint;
          break;
        case "purchase":
          getFunc = purchase_print;
          break;
        case "purchase_return":
          getFunc = purchase_return_print;
          break;
        case "sort":
          getFunc = sort_print;
          break;
        case "receivables":
          getFunc = statement_print;
          break;
        case "account":
          getFunc = account_list_print;
          break;
        case "advice":
          // 采购结算
          getFunc = advice_list_print;
          break;
        case "sortuser":
          getFunc = sort_user_print;
          break;
        case "cash_delivery_order":
          getFunc = cash_delivery_order_print;
          break;
        case "online_payment_order":
          getFunc = online_payment_order_print;
          break;
        case "order_return":
          getFunc = order_return_print;
          break;
        case "other_user_order":
          getFunc = batch_unbind_print;
          break;
        case "other_user_completed_order":
          getFunc = printEmpty;
          break;
        case "storage":
          getFunc = storage_print;
          break;
        case "stockout":
          getFunc = stockout_print;
          break;
      }
      try {
        await getFunc(data).then(res => {
          if(res.errcode != 0) throw res.errmsg;
          let data = res.list;
          this.all = data.all;
          this.main_settings = JSON.parse(data.mubang.main_settings);
          this.print_settings = JSON.parse(data.mubang.print_settings);
          this.lineNumber = this.print_settings.printSetting.lineNumber || 10;
          this.tableTrHeight = this.print_settings.printSetting.tableTrHeight || 25;
          this.showPageHeader = this.print_settings.printSetting.showPageHeader;
  
          let topMargin = this.print_settings.printSetting.topMargin;
          this.topMargin = Number(topMargin) + 25;
          this.order = data.order;
          this.order_list = [];
          this.tem_id = data.mubang.tem_id;
          if (type == "order" && this.print_settings.printSetting.is_category) {
            let arr = [];
            data.order_list1.map(e => {
              arr.push({
                category_name: e.category_name,
                class: e.class,
                money: e.money
              });
            });
            this.category_list = arr;
            this.order_list = this.handleCategory(data.order_list1);
          } else {
            if (
              this.tem_id == 9 &&
              this.print_settings.printSetting.doublePrinting == 1
            ) {
              this.newtablist = this.main_settings.find(item => item.type == 'table').columns;
              let len = Object.keys(data.order_list).length;
  
              if (this.showPageHeader == true) {
                //开启双排和分页
                if (len % 2 == 0) {
                  this.order_list = this.group(
                    data.order_list,
                    this.lineNumber
                  );
                } else {
                  let arr = data.order_list;
                  let newlist = arr[1];
                  const arr2 = new Array(newlist.length).fill(null);
                  arr2[0] = len + 1;
                  let key = len + 1;
                  let value = arr2;
                  arr[key] = value;
                  this.order_list = this.group(
                    data.order_list,
                    this.lineNumber
                  );
                }
              } else {
                //只开启双排
                if (len % 2 == 0) {
                  this.order_list = this.group(
                    data.order_list,
                    this.lineNumber
                  );
                } else {
                  let arr = data.order_list;
                  let newlist = arr[1];
                  const arr2 = new Array(newlist.length).fill(null);
                  arr2[0] = len + 1;
                  let key = len + 1;
                  let value = arr2;
                  arr[key] = value;
                  this.order_list = this.group(
                    data.order_list,
                    this.lineNumber
                  );
                }
              }
            } else {
              this.order_list = this.group(data.order_list, this.lineNumber);
            }
          }
          this.show = true;
  
          this.print_set_info.map(item => {
            if (item.type == data.mubang.tem_id) {
              this.print_settings.print_mark = item.print_index;
            }
          });
          let arr = []
          this.main_settings.forEach(item=>{
            if (item.type=='sign') {
              arr.push(item.top);
              this.signHeight = arr.reduce((a, b) => Math.max(a, b));
            } else if (item.type=='table'){
              this.tableHeight = parseInt(item.containerStyle.top);
            }
          })
          this.$nextTick(async () => {
            try {
              await this.generateQRCode(res.list.qrCodeUrl, 80, 80);  // 如果此处报错，捕获异常
            } catch (error) {
              console.error('二维码生成失败:', error);  // 可以打印错误信息或者进行其他处理
            }
            this.print(this.print_settings);
          });
        });
      } catch (e) {
        this.$message.error(e);
      }
    },
    // 生成二维码
    generateQRCode(url, width, height) {
      return new Promise((resolve, reject) => {
        let qrcode = new QRCode("qrcode", {
          text: url,
          width: width,
          height: height,
        });
        // 等待100毫秒以确保二维码已经生成
        setTimeout(() => {
          resolve();
        }, 100);
      });
    },
    // 订单打印事件
    print(params) {
      let LODOP = getLodop();
      if (!LODOP) {
        return;
      }
      if (params.print_mark != -1) {
        LODOP.SET_PRINTER_INDEX(params.print_mark);
      }
      LODOP.SET_PRINT_PAGESIZE(
        1,
        params.page.width + "mm",
        params.page.height + "mm",
        params.page.headerTitle
      );
      LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true); //设置页面缩放

      let isLeftTurn = this.print_settings.printSetting.isLeftTurn90;

      if (this.tem_id == 9 && isLeftTurn == true) {
        LODOP.ADD_PRINT_HTM(
          params.printSetting.topMargin + "px",
          params.printSetting.leftMargin + "px",
          "52%",
          "100%",
          document.getElementById("main").innerHTML
        );
        LODOP.SET_PRINT_STYLEA(0, "AngleOfPageInside", 90);
      } else {
        LODOP.SET_PRINT_STYLEA(0, "Vorient", 0);
        LODOP.ADD_PRINT_HTM(
          params.printSetting.topMargin + "px",
          params.printSetting.leftMargin + "px",
          "100%",
          "100%",
          document.getElementById("main").innerHTML
        );
      }

      if ((params.printSetting.isShow && !this.continuous) || this.preview) {
        LODOP.PREVIEW();
      } else {
        LODOP.PRINT();
      }
      this.$nextTick(()=>{
        // 清空二维码
        if(document.getElementById("qrcode")) document.getElementById("qrcode").innerHTML = "";
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
